package net.weitalk.metrics.v3;

import java.util.*;
import java.util.function.Function;
import java.util.function.ToDoubleFunction;
import java.util.stream.Collectors;

import static java.util.Collections.max;
import static java.util.Collections.min;

public class Aggregator {
    
    public Map<String, RequestStat> aggregate(
            Map<String, List<RequestInfo>> requestInfos,
            long durationInMillis
    ) {
        Map<String, RequestStat> stats = new HashMap<>();
        for (Map.Entry<String, List<RequestInfo>> entry : requestInfos.entrySet()) {
            String apiName = entry.getKey();
            List<RequestInfo> requestInfoList = entry.getValue();
            RequestStat requestStat = doAggregate(requestInfoList, durationInMillis);
            stats.put(apiName, requestStat);
        }
        return stats;
    }
    
    public RequestStat doAggregate(List<RequestInfo> requestInfos, long durationInMillis) {
        List<Double> responseTimes = requestInfos.stream()
                .map(RequestInfo::getResponseTime)
                .collect(Collectors.toList());
        
        RequestStat requestStat = new RequestStat();
        requestStat.setMaxResponseTime(max(responseTimes));
        requestStat.setMinResponseTime(min(responseTimes));
        requestStat.getAvgResponseTime(avg(responseTimes));
        requestStat.setP999ResponseTime(p999(responseTimes));
        requestStat.setP99ResponseTime(p99(responseTimes));
        requestStat.setCount(responseTimes.size());
        requestStat.setTps(tps(responseTimes.size(), durationInMillis));
        return requestStat;
    }

    private long tps(int size, long durationInMillis) {
        return size / (durationInMillis * 1000);
    }

    private double p99(List<Double> responseTimes) {
        return 0.0;
    }

    private double p999(List<Double> responseTimes) {
        return 0.0;
    }

    private double avg(List<Double> responseTimes) {
        return responseTimes.stream().mapToDouble(a -> a).average().orElse(Double.NaN);
    }
}
